package com.qianbei.view.transport;

import android.annotation.SuppressLint;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.PowerManager;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.google.gson.Gson;
import com.qianbei.R;
import com.qianbei.bean.ChangeCarBean;
import com.qianbei.bean.ChangeStationBean;
import com.qianbei.bean.GetNamebean;
import com.qianbei.bean.RequeastBean1;
import com.qianbei.common.base.BaseActivity;
import com.qianbei.common.base.Basebean;
import com.qianbei.common.base.MyApplication;
import com.qianbei.common.init.SetData;
import com.qianbei.common.net.control.ServerControl;
import com.qianbei.common.net.control.ServerResult;
import com.qianbei.common.net.okhttp.RequeastBean;
import com.qianbei.common.net.view.MsgAlert;
import com.qianbei.common.net.view.ProgressDialog;
import com.qianbei.common.util.DeviceUtil;
import com.qianbei.view.orm.DaoSession;
import com.qianbei.view.orm.RequestPersistent;
import com.speedata.libuhf.IUHFService;
import com.speedata.libuhf.bean.SpdInventoryData;
import com.speedata.libuhf.interfaces.OnSpdInventoryListener;

import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * <pre>
 *     author : pipi
 *     e-mail : xxx@xx
 *     time   : 2018/12/14
 *     desc   :
 *     version: 1.0
 * </pre>
 */

public class ChangeCarActivity extends BaseActivity {
    @Bind(R.id.tv_rfid)
    TextView mTvRfid;
    @Bind(R.id.tv_change)
    TextView mTvChange;
    @Bind(R.id.et_big)
    EditText mEtBig;
    @Bind(R.id.et_small)
    EditText mEtSmall;
    private AtomicBoolean isOpenDev = new AtomicBoolean(false);
    private IUHFService iuhfService;
    boolean ishow = false;
    private int init_progress = 0;
    private PowerManager pM = null;
    private PowerManager.WakeLock wK = null;
    public static final String TAG = ChangeCarActivity.class.getSimpleName();
    private List<ChangeStationBean> stationBeans;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_change_car);
        ButterKnife.bind(this);
        setTitle("换车");
        mTitle.setrightTitle("扫描");
        initUHFService();
    }

    @SuppressLint("StaticFieldLeak")
    @Override
    public void fClick(int id) {
        super.fClick(id);
        switch (id) {
            case R.id.tv_right:
                scan();
                break;
        }
    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 111:
                    SpdInventoryData var1 = (SpdInventoryData) msg.obj;
                    mTitle.setrightTitle("扫描");
                    Log.d(TAG, var1.epc);
                    if (!ishow) {
                        ishow = true;
                        if (var1 != null && !TextUtils.isEmpty(var1.epc)) {
                            mTvRfid.setText(var1.epc);
                        }
                    }
                    break;
            }
        }
    };

    private void initUHFService() {
        iuhfService = MyApplication.iuhfService;
        iuhfService.setOnInventoryListener(new OnSpdInventoryListener() {
            @Override
            public void getInventoryData(SpdInventoryData var1) {

                if (!ishow) {
                    handler.sendMessage(handler.obtainMessage(111, var1));
                }

            }
        });
        newWakeLock();
    }

    private void newWakeLock() {
        init_progress++;
        pM = (PowerManager) getSystemService(POWER_SERVICE);
        if (pM != null) {
            wK = pM.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK
                    | PowerManager.ON_AFTER_RELEASE, "lock3992");
            if (wK != null) {
                wK.acquire();
                init_progress++;
            }
        }
        if (init_progress == 1) {
            Log.w("3992_6C", "wake lock init failed");
        }
    }

    private void scan() {
        mTitle.setrightTitle("正在扫描");
        ishow = false;
        //重复点扫描按钮时 只做一次上电操作
        if (isOpenDev.get() == false) {
            isOpenDev.set(true);
            new AsyncTask<Void, Void, Void>() {
                @Override
                protected Void doInBackground(Void... voids) {
                    try {
                        if (iuhfService != null) {
                            if (openDev()) {
                                isOpenDev.set(false);
                                return null;
                            }
                        }
                        iuhfService.set_antenna_power(MyApplication.setValue);
                    } catch (Exception e) {
                        e.printStackTrace();
                        isOpenDev.set(false);
                        return null;
                    }

                    if (iuhfService == null) {
                        initUHFService();
                    }
                    iuhfService.newInventoryStart();
                    return null;
                }
            }.execute();
        }
    }

    /**
     * 上电开串口
     *
     * @return
     */
    private boolean openDev() {
        if (iuhfService.OpenDev() != 0) {
            new android.app.AlertDialog.Builder(this).setTitle(R.string.DIA_ALERT).setMessage(R.string.DEV_OPEN_ERR).setPositiveButton(R.string.DIA_CHECK, new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    // TODO Auto-generated method stub
                    finish();
                }
            }).show();
            return true;
        }
        return false;
    }

    @Override
    protected void onStop() {
        super.onStop();
        try {
            if (iuhfService != null && isOpenDev.get() == true) {
                iuhfService.newInventoryStop();
                iuhfService.CloseDev();
                //断电后选卡操作会失效，需要重新选卡（掩码）
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @OnClick({R.id.tv_save, R.id.rl})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_save:
                if (TextUtils.isEmpty(mTvRfid.getText().toString())) {
                    new MsgAlert().show("请先扫描换车的RFID");
                    return;
                }
                if (TextUtils.isEmpty(mTvChange.getText().toString()) || index == -1) {
                    new MsgAlert().show("请选择中转站");
                    return;
                }
                if (TextUtils.isEmpty(mEtBig.getText().toString())) {
                    new MsgAlert().show("请填写大箱数量");
                    return;
                }
                if (TextUtils.isEmpty(mEtSmall.getText().toString())) {
                    new MsgAlert().show("请填写小箱数量");
                    return;
                }
                iuhfService.newInventoryStop();
                changeCar();
                break;
            case R.id.rl:
                chooseChange();
                break;
        }
    }

    private void chooseChange() {
        if (stationBeans == null) {
            RequeastBean bean =
                    new RequeastBean1("select", "com.cygps.dubbo.commons.data.ICommonDataService",
                            new Basebean(), "WT_TransferStation");
            ServerControl sc = new ServerControl(bean);
            sc.serverListener = new ServerControl.ServerListener() {
                @Override
                public void serverFinish(ServerResult sr) {
                    if (sr.isContinue) {
                        try {
                            org.json.JSONArray js = sr.bodyData.optJSONArray("array");
                            stationBeans = JSON.parseArray(js.toString(), ChangeStationBean.class);
                            showChooseDialog(stationBeans);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
            };
            new ProgressDialog(mContext).OKpost1(sc, "加载中...");
        } else {
            showChooseDialog(stationBeans);
        }
    }
    private int index = -1;
    private void showChooseDialog(List<ChangeStationBean> stationBeans) {
        index = -1;
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("选择中转站");
        final String[] texts = new String[stationBeans.size()];
        for (int i = 0; i < stationBeans.size(); i++) {
            texts[i] = stationBeans.get(i).getName();
        }
        builder.setSingleChoiceItems(texts, -1, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                index = which;
            }
        })
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (index != -1) {
                            mTvChange.setText(texts[index]);
                        }
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                })
                .show();
    }

    /**
     * 换车接口
     */
    private void changeCar() {
        String jobId = SetData.getJobid();
        if (TextUtils.isEmpty(jobId)) {
            new MsgAlert().show("请退出重新绑定车辆");
            return;
        }
        String rfid = mTvRfid.getText().toString();
        String bigText = mEtBig.getText().toString();
        String smallText = mEtSmall.getText().toString();
        String trsferId = stationBeans.get(index).get_id();
        int big = 0;
        int small = 0;
        try {
            big = Integer.parseInt(bigText);
            small = Integer.parseInt(smallText);
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
        RequeastBean bean =
                new RequeastBean("changeVehicle", "com.cygps.dubbo.WasteTransport.IPdaBoxnullAndLoadandunloadScan",
                        new ChangeCarBean(jobId, rfid, big, small, trsferId));
        if (!DeviceUtil.isNetworkAvailable()) {
            DaoSession daoSession = ((MyApplication) getApplication()).getDaoSession();
            RequestPersistent requestPersistent = new RequestPersistent();
            requestPersistent.setServiceName(bean.serviceName);
            requestPersistent.setServiceMethod(bean.serviceMethod);
            requestPersistent.setServiceBody(new Gson().toJson(bean.serviceBody));
            requestPersistent.setMethodClass(ChangeCarBean.class.getName());
            daoSession.getRequestPersistentDao().insertOrReplace(requestPersistent);
            new MsgAlert().show("换车成功");
            finish();
        } else {
            ServerControl sc = new ServerControl(bean);
            sc.serverListener = new ServerControl.ServerListener() {
                @Override
                public void serverFinish(ServerResult sr) {
                    if (sr.isContinue) {
                        new MsgAlert().show("换车成功");
                        finish();
                    }
                }
            };
            new ProgressDialog(mContext).OKpost(sc);
        }
    }
}
